package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.PageBean;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysUserDto;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ZhuHongKai
 * @version 1.0
 * @ClassName UserSysController
 * @date 2022/10/12 11:36
 */
@RestController
@RequestMapping("/sys_user")
@Slf4j
public class SysUserController {
    @Autowired
    private ISysUserService userSysService;

    @Autowired
    private ISysRoleService roleService;

    /**
     * 系统角色列表数据
     * @param login_name
     * @param status
     * @param phone
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public ResultData list(String login_name,String status,String phone,Integer page,Integer limit){
        Page<SysUser> pageInfo = new Page<>(page,limit);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(login_name),SysUser::getLoginName,login_name);
        queryWrapper.like(StringUtils.hasText(status),SysUser::getStatus,status);
        queryWrapper.like(StringUtils.hasText(phone),SysUser::getPhone,phone);
        userSysService.page(pageInfo,queryWrapper);
        List<SysUser> records = pageInfo.getRecords();
        Page<SysUserDto> userDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo,userDtoPage,"records");

        List<SysUserDto> sysUserDtoStream = records.stream().map(user -> {
            SysUserDto userDto = new SysUserDto();
            BeanUtils.copyProperties(user, userDto);
            String roleId = user.getRoleId();
            String s = roleId.substring(1, roleId.length() - 1);
            String substring = s.substring(1, s.length() - 1);
            List<String> strings = roleService.roleNameList(substring);
            List<String> stringid = roleService.roleIdList(substring);
            userDto.setRolename(strings);
            userDto.setRole_id(stringid);
            return userDto;
        }).collect(Collectors.toList());
        userDtoPage.setRecords(sysUserDtoStream);

        PageBean<SysUserDto> pageBean = new PageBean<>();
        pageBean.setCurrentPage(userDtoPage.getCurrent()); // 当前页
        pageBean.setData(userDtoPage.getRecords()); // 封装的具体数据集合
        pageBean.setPageSize(userDtoPage.getSize()); // 每页显示条数
        pageBean.setCount(userDtoPage.getTotal()); // 总记录数(总条数)
        pageBean.setTotalPages(userDtoPage.getPages()); // 总页数
        return ResultData.ok("",pageBean);
    }

    /**
     * 添加管理员
     * @param sysUserDto
     * @return
     */
    @PostMapping("/add")
    public ResultData add(@RequestBody SysUserDto sysUserDto){
        log.info("sysUserDto= {}",sysUserDto);
        List<String> roleId = sysUserDto.getRole_id();
        String role_id = "[\"";
        for (String s : roleId) {
            s += ",";
            role_id += s;
        }
        role_id += "1";
        int index = role_id.lastIndexOf(",");
        char[] chars = role_id.toCharArray();
        chars[index] = '"';
        chars[index + 1] = ']';
        role_id = String.valueOf(chars);
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDto,sysUser,"role_id");
        sysUser.setRoleId(role_id);
        sysUser.setCreateDate(LocalDateTime.now());
        sysUser.setUpdateDate(LocalDateTime.now());
        userSysService.save(sysUser);
        return ResultData.ok("添加成功",200);
    }

    /**
     * 删除员工管理
     * @param id
     * @return
     */
    @GetMapping("/del")
    public ResultData del(String id){
        userSysService.removeById(id);
        return ResultData.ok("200", 200);
    }

    /**
     * 修改数据回显接口
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id){
        log.info("id={}",id);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getId,id);
        SysUser one = userSysService.getOne(queryWrapper);
        String[] rowIds = one.getRoleId().replace("[", "").replace("]", "").replace("\"", "").split(",");
        List<String> ids = new ArrayList<>();
        Collections.addAll(ids,rowIds);

        SysUserDto userDto = new SysUserDto();
        BeanUtils.copyProperties(one,userDto);
        userDto.setRole_id(ids);
        return ResultData.ok("200",userDto);
    }

    @PostMapping("/update")
    public ResultData update(@RequestBody SysUserDto sysUserDto){
        log.info("user={}", sysUserDto);
        List<String> roleId = sysUserDto.getRole_id();
        if (roleId != null) {
            String role_id = "[\"";
            for (String s : roleId) {
                s += ",";
                role_id += s;
            }
            role_id += "1";
            int index = role_id.lastIndexOf(",");
            char[] chars = role_id.toCharArray();
            chars[index] = '"';
            chars[index + 1] = ']';
            role_id = String.valueOf(chars);
            // 封装数据
            SysUser sysUser = new SysUser();
            sysUser.setId(sysUserDto.getId());
            sysUser.setLoginName(sysUserDto.getLoginName());
            sysUser.setPassword(sysUserDto.getPassword());
            sysUser.setName(sysUserDto.getName());
            sysUser.setEmail(sysUserDto.getEmail());
            sysUser.setPhone(sysUserDto.getPhone());
            sysUser.setLoginIp(sysUserDto.getLoginIp());
            sysUser.setCreateDate(sysUserDto.getCreateDate());
            sysUser.setUpdateDate(sysUserDto.getUpdateDate());
            sysUser.setDelFlag(sysUserDto.getDelFlag());
            sysUser.setRoleId(role_id);
            sysUser.setStatus(sysUserDto.getStatus());
            sysUser.setDefaultData(sysUserDto.getDefaultData());
            // 调用service
            userSysService.updateById(sysUser);
            return ResultData.ok("修改成功",null);
        } else {
            LambdaUpdateWrapper<SysUser> queryWrapper = new LambdaUpdateWrapper<>();
            queryWrapper.eq(SysUser::getId,sysUserDto.getId());
            queryWrapper.set(SysUser::getStatus,sysUserDto.getStatus());
            userSysService.update(queryWrapper);
            return ResultData.ok("修改成功",null);
        }
    }
}
